package com.mishow.activity.base;

import java.lang.reflect.Field;

import org.json.JSONException;
import org.json.JSONObject;

import com.mishow.R;
import com.mishow.log.MyLog;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.DeviceUtil;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage.QuotaUpdater;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ZoomButtonsController;
/**
 * 
 * 作者：wei.miao <br/>
 * 描述：WebView界面基类
 */
@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
public abstract class WebViewBaseActivity extends BaseActivity {

    protected final static int OPEN_ACTIVITY = 0;// 跳转界面
    protected final static int INCOMINT_DATA = 1;// 传入数据到JS
    protected final static int OUTCOMINT_DATA = 2;// 从JS获取数据
    protected final static int SHOW_ALERT = 3;// 显示Alert对话框
    protected final static int SHOW_TOAST = 4;// 显示一个toast提示
    protected final static int SHOW_LOADING = 5;// 显示加载中的状态
    protected final static int HIDE_LOADING = 6;// 隐藏加载中的状态
    protected final static int COPY_STRING = 7;// 复制字符窜

//    protected final static int COMMON_OPEN_ACTIVITY = 100;// 页面跳转统一接口

    private Handler mHandler = new Handler();
    private Dialog mProgressDialog;// 加载进度 对话框
    protected ValueCallback<Uri> mUploadMsg;
    protected ValueCallback<Uri[]> mUploadCallbackAboveL;

    // 是否激活返回键处理方式
    protected boolean activeCallBack = false;

    /**
     * JS接口回调
     */
    protected void jsInterface(int model, String handler, String jsonData, String callbackId) {
    }

    /**
     * 加载html错误回调接口
     */
    protected void webViewClientError(int errorCode, String description) {

    }

    /**
     * 显示加载中
     *
     * @param showLoading
     */
    protected void showWebViewLoading(boolean showLoading) {
    }

    @SuppressLint("JavascriptInterface")
    public void initWebView(WebView webView) {
        WebSettings websettings = webView.getSettings();

        // 开启javascript设置
        websettings.setJavaScriptEnabled(true);

        // 不使用缓存
        websettings.setAppCacheEnabled(true);
        // 缓存最多可以有8M()过时方法
        //websettings.setAppCacheMaxSize(1024 * 1024 * 8);
        
        String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        websettings.setAppCachePath(appCacheDir);

        // 应用可以有数据库
        websettings.setDatabaseEnabled(true);
        String dbPath = getApplicationContext().getCacheDir().getAbsolutePath();
        /*
         * this.getApplicationContext() .getDir("database",
		 * Context.MODE_PRIVATE).getPath()
		 */
        //过时方法
        //websettings.setDatabasePath(dbPath);

        // 启用地理定位
        websettings.setGeolocationEnabled(true);
        // 设置定位的数据库路径
        websettings.setGeolocationDatabasePath(dbPath);

        // 设置可以使用localStorage
        websettings.setDomStorageEnabled(true);
        // 可以读取文件缓存(需要服务器配置manifest生效)
        websettings.setAllowFileAccess(true);
        // 不使用缓存
        websettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 允许放大缩小
        websettings.setSupportZoom(false);
        // 显示放大缩小按钮
        websettings.setBuiltInZoomControls(false);
        hideZoomController(websettings, webView);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.addJavascriptInterface(new JavaScriptInterface(), "androidWeb");
        // webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        setUserAgent(websettings);
    }

    /**
     * WebView追加UserAgent
     *
     * @param websettings
     */
    private void setUserAgent(WebSettings websettings) {
        StringBuffer sb = new StringBuffer(websettings.getUserAgentString());
        sb.append(" " + (int) DeviceUtil.getDeviceHight(this) + "*" + (int) DeviceUtil.getDeviceWidth(this));
        sb.append(" " + "KKMY_U/" + AndroidUtil.getVersionName(this));
        websettings.setUserAgentString(sb.toString());
        MyLog.d("com.mishow", "ua = " + websettings.getUserAgentString());
    }

    // 与js进行交互的接口
    final class JavaScriptInterface {
        /*
         * js调用本地方法,传参数in进来,in代表页面调用的接口-不可删除
         */
        public void execute(final String result) {
            mHandler.post(new Runnable() {

                public void run() {
                    JSONObject object;
                    try {
                        object = new JSONObject(result);
                        int model = -1;
                        String handler = "";
                        String jsonData = "";
                        String callbackId = "";
                        if (object.has("handler")) {
                            handler = object.getString("handler");
                        }
                        if (object.has("jsonData")) {
                            jsonData = object.getString("jsonData");
                        }
                        if (object.has("callbackId")) {
                            callbackId = object.getString("callbackId");
                        }
                        model = Integer.parseInt(object.getString("model"));
                        jsInterface(model, handler, jsonData, callbackId);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }
    
    final class MyWebViewClientText extends WebViewClient{
    	
    	
    	
    	
    }

    final class MyWebViewClient extends WebViewClient {
    	
    	
        /**
         * 对网页中超链接按钮的响应
         * 
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            activeCallBack = false;
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            MyLog.d("com.rogrand.kkmy", "onPageFinished");
            // dismissProgress();
            showWebViewLoading(false);
            view.loadUrl("javascript:webMutual.activePlatform()");
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            // showProgress(null, null, true);
            showWebViewLoading(true);
        }

        /**
         * 统一处理 webview 加载错误时处理
         */
        private void showWebError(WebView view, String url) {
            if (url == null || url.endsWith("/favicon.ico") || url.endsWith("/[object%20Object]")) {
                //忽略由于 favicon 和 rcp 请求导致的错误
                return;
            }
            showWebViewLoading(false);
            view.stopLoading();
            view.clearView();
            webViewClientError(0, "");
        }

        /**
         * 
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            MyLog.d("webview", "onReceivedError:" + failingUrl);
            showWebError(view, failingUrl);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            handler.proceed();//接受证书
        }
    
    }

    /**
     * 描述：设置加载进度
     */
    final class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
            super.onGeolocationPermissionsShowPrompt(origin, callback);
            callback.invoke(origin, true, false);
        }

        // 扩充缓存的容量
        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) {
            quotaUpdater.updateQuota(requiredStorage * 2);
        }

        // 扩充数据库的容量
        @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota,
                                            long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
            quotaUpdater.updateQuota(estimatedDatabaseSize * 2);
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooserCallBack(uploadMsg, null, acceptType);
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

        // For Android 5.0+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                         WebChromeClient.FileChooserParams fileChooserParams) {
            openFileChooserCallBack(null, filePathCallback, "");
            return true;
        }
    }

    private void hideZoomController(WebSettings websettings, WebView webView) {
        if (hideZoomByHoneycombApi(websettings)) {
            return;
        }

        hideZoomByReflection(webView);
    }

    private boolean hideZoomByHoneycombApi(WebSettings websettings) {
        if (Build.VERSION.SDK_INT < 11) {
            return false;
        }

        websettings.setDisplayZoomControls(false);
        return true;
    }

    public void hideZoomByReflection(WebView webView) {
        Class<?> classType;
        Field field;
        try {
            classType = WebView.class;
            field = classType.getDeclaredField("mZoomButtonsController");
            field.setAccessible(true);
            ZoomButtonsController mZoomButtonsController = new ZoomButtonsController(webView);
            mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
            try {
                field.set(webView, mZoomButtonsController);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示等待框
     *
     * @param title
     * @param message
     */
    public void showProgress(String title, String message, boolean isCancel) {
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                return;
            }
            mProgressDialog = new Dialog(this, R.style.CustomDialog);
            mProgressDialog.setContentView(R.layout.dialog_progress);
            mProgressDialog.setCancelable(isCancel);
//            TextView textView = (TextView) mProgressDialog.findViewById(R.id.progress_msg);
//            if (TextUtils.isEmpty(message)) {
//                textView.setVisibility(View.GONE);
//            } else {
//                textView.setVisibility(View.VISIBLE);
//                textView.setText(message);
//            }
            mProgressDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消等待框
     */
    public void dismissProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            try {
                mProgressDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, ValueCallback<Uri[]> filePathCallback, String acceptType) {
    }
}
